#region File Description
//-----------------------------------------------------------------------------
// GameplayScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Collections.Generic;

using CreamX.Framework.Game.GameEngine;

using CreamX.Framework.Game;
using CreamX.Framework.Text;
using Microsoft.Xna.Framework.Net;
using CreamX.Framework.Networking;



#endregion

namespace CreamX.Framework.GameState.Screens
{

   public class GameplayScreen : GameScreen
    {
        #region Fields

        public NetworkSession networkSession;

        ContentManager content;
        SpriteFont gameFont;

        #endregion

        #region Properties


        /// <summary>
        /// The logic for deciding whether the game is paused depends on whether
        /// this is a networked or single player game. If we are in a network session,
        /// we should go on updating the game even when the user tabs away from us or
        /// brings up the pause menu, because even though the local player is not
        /// responding to input, other remote players may not be paused. In single
        /// player modes, however, we want everything to pause if the game loses focus.
        /// </summary>
        new bool IsActive
        {
            get
            {
                if (networkSession == null)
                {
                    // Pause behavior for single player games.
                    return base.IsActive;
                }
                else
                {
                    // Pause behavior for networked games.
                    return !IsExiting;
                }
            }
        }


        #endregion

        #region Initialization


        /// <summary>
        /// Constructor.
        /// </summary>
        public GameplayScreen(NetworkSession networkSession)
        {
            this.networkSession = networkSession;

            TransitionOnTime = TimeSpan.FromSeconds(1.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
        }


        /// <summary>
        /// Load graphics content for the game.
        /// </summary>
        public override void LoadContent()
        {
            if (content == null)
                content = new ContentManager(ScreenManager.Game.Services, "Content");

            gameFont = CreamXGame.Instance.embeddedcontent.Load<SpriteFont>("gamefont");

            base.LoadContent();
            
            LoadGameData();
            // once the load has finished, we use ResetElapsedTime to tell the game's
            // timing mechanism that we have just finished a very long frame, and that
            // it should not try to catch up.
            ScreenManager.Game.ResetElapsedTime();
        }


        /// <summary>
        /// Unload graphics content used by the game.
        /// </summary>
        public override void UnloadContent()
        {
            content.Unload();
            UnLoadGameData();
        }


        #endregion

        #region Update and Draw


        /// <summary>
        /// Updates the state of the game.
        /// </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                                       bool coveredByOtherScreen)
        {


            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            if (IsActive)
            {
                DoMainUpdate(gameTime);
                // TODO: this game isn't very fun! You could probably improve
                // it by inserting something more interesting in this space :-)
            }

            // If we are in a network game, check if we should return to the lobby.
            if ((networkSession != null) && !IsExiting)
            {
                if (networkSession.SessionState == NetworkSessionState.Lobby)
                {
                    LoadingScreen.Load(ScreenManager, true,
                                       new BackgroundScreen(),
                                       new LobbyScreen(networkSession));
                }
            }
        }


        /// <summary>
        /// Lets the game respond to player input. Unlike the Update method,
        /// this will only be called when the gameplay screen is active.
        /// </summary>
        public override void HandleInput(GameTime gameTime, InputState input)
        {
            if (input == null)
                throw new ArgumentNullException("input");

            if (input.PauseGame)
            {
                // If they pressed pause, bring up the pause menu screen.
                ScreenManager.AddScreen(new PauseMenuScreen(networkSession));
            }
            else
            {
                // Otherwise move the player position.
                Vector2 movement = Vector2.Zero;

                for (int i = 0; i < InputState.MaxInputs; i++)
                {
                    if (input.CurrentKeyboardStates[i].IsKeyDown(Keys.Left))
                        movement.X--;

                    if (input.CurrentKeyboardStates[i].IsKeyDown(Keys.Right))
                        movement.X++;

                    if (input.CurrentKeyboardStates[i].IsKeyDown(Keys.Up))
                        movement.Y--;

                    if (input.CurrentKeyboardStates[i].IsKeyDown(Keys.Down))
                        movement.Y++;

                    Vector2 thumbstick = input.CurrentGamePadStates[i].ThumbSticks.Left;

                    movement.X += thumbstick.X;
                    movement.Y -= thumbstick.Y;
                }

                if (movement.Length() > 1)
                    movement.Normalize();

                //playerPosition += movement * 2;
            }
        }


        /// <summary>
        /// Draws the gameplay screen.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            //// This game has a blue background. Why? Because!
            //ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
            //                                   Color.CornflowerBlue, 0, 0);

            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
      
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend,SpriteSortMode.Deferred,SaveStateMode.None);
            
            Draw(gameTime, spriteBatch);
            spriteBatch.End();

            // If the game is transitioning on or off, fade it out to black. 
            if (TransitionPosition > 0)
                ScreenManager.FadeBackBufferToBlack(255 - TransitionAlpha);
        }
       public virtual void Draw(GameTime gameTime, SpriteBatch batch)
       {
           CreamXGame.Instance.GameTime = gameTime;
           if (ScreenState == ScreenState.Active && TransitionPosition == 0)
           {
               if (CreamXGameEngine.Instance.SceneManager.CurrentScene != null)
               {
                   CreamXGameEngine.Instance.EngineRender((float)gameTime.ElapsedGameTime.TotalSeconds, batch);
               }
           }
           if (TransitionPosition > 0)
               ScreenManager.FadeBackBufferToBlack(255 - TransitionAlpha,batch);
       }
       
        private void DoMainUpdate(GameTime gameTime)
        {
            CreamXGame.Instance.GameTime = gameTime;
            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
            
            CreamXGameEngine.Instance.EngineUpdate(elapsed);    
        }
        #endregion
        public virtual void LoadGameData()
        {
        }
        public virtual void UnLoadGameData()
        {
        }

    }
    ///// <summary>
    ///// This screen implements the actual game logic. It is just a
    ///// placeholder to get the idea across: you'll probably want to
    ///// put some more interesting gameplay in here!
    ///// </summary>
    //public class GameplayScreen : GameScreen
    //{
    //    SpriteBatch _spriteBatch;
    //    public static GameplayScreen BaseInstance;
    //    public Microsoft.Xna.Framework.Graphics.GraphicsDevice GraphicsDevice
    //    {
    //        get { return ScreenManager.GraphicsDevice; }
    //    }
    //    #region Initialization

    //    ContentManager content;
    //    public ContentManager Content
    //    {
    //        get { return content; }
    //    }
    //    SpriteFont gameFont;
    //    /// <summary>
    //    /// Constructor.
    //    /// </summary>
    //    public GameplayScreen()
    //    {
            
    //        TransitionOnTime = TimeSpan.FromSeconds(1.5);
    //        TransitionOffTime = TimeSpan.FromSeconds(0.5);
            
    //    }
        

    //    /// <summary>
    //    /// Load graphics content for the game.
    //    /// </summary>
    //    public override void LoadContent()
    //    {

    //        _spriteBatch = new SpriteBatch(GraphicsDevice);
    //        if (content == null)
    //            content = new ContentManager(ScreenManager.Game.Services);

    //        gameFont = TextEngine.Instance.Fonts[(int)FontNames.GameFont];

    //        base.LoadContent();
            
    //        LoadGameData();
    //        // once the load has finished, we use ResetElapsedTime to tell the game's
    //        // timing mechanism that we have just finished a very long frame, and that
    //        // it should not try to catch up.
    //        ScreenManager.Game.ResetElapsedTime();
    //    }
        
    //    public virtual void LoadGameData()
    //    {
    //    }
    //    public virtual void UnLoadGameData()
    //    {
    //    }

    //    /// <summary>
    //    /// Unload graphics content used by the game.
    //    /// </summary>
    //    public override void UnloadContent()
    //    {
    //        content.Unload();
    //        UnLoadGameData();
    //    }


    //    #endregion

    //    #region Update and Draw
        
    //    /// <summary>
    //    /// Updates the state of the game. This method checks the GameScreen.IsActive
    //    /// property, so the game will stop updating when the pause menu is active,
    //    /// or if you tab away to a different application.
    //    /// </summary>
    //    public override void Update(GameTime gameTime, bool otherScreenHasFocus,
    //                                                   bool coveredByOtherScreen)
    //    {
    //        if (CreamXGameEngine.Instance.CurrentScene== null)
    //            return;
            

    //        base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

    //        if (IsActive)
    //        {
    //            CreamXProfiler.StartProfiling(ProfilerName.GameplayScreenUpdate);
    //            DoMainUpdate(gameTime);
    //            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
    //            CreamXProfiler.StopProfiling(ProfilerName.GameplayScreenUpdate);
    //        }
            
    //    }

        
    //    private void DoMainUpdate(GameTime gameTime)
    //    {
    //        // Allows the game to exit
    //        //if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
    //          //  this.Exit();

    //        CreamXGame.Instance.GameTime = gameTime;
    //        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
    //        CreamXGameEngine.Instance.EngineUpdate(elapsed);    
            
    //        //base.Update(gameTime);
    //    }
        
    //    /// <summary>
    //    /// Lets the game respond to player input. Unlike the Update method,
    //    /// this will only be called when the gameplay screen is active.
    //    /// </summary>
    //    public override void HandleInput(GameTime gameTime, InputState input)
    //    {
    //        if (input == null)
    //            throw new ArgumentNullException("input");



    //        base.HandleInput(gameTime, input);
    //    }


    //    /// <summary>
    //    /// Draws the gameplay screen.
    //    /// </summary>
    //    public override void Draw(GameTime gameTime)
    //    {
    //        ScreenManager.SpriteBatch.Begin(SpriteBlendMode.AlphaBlend, 
    //            SpriteSortMode.Deferred, SaveStateMode.None);
    //        //ScreenManager.SpriteBatch.GraphicsDevice.SamplerStates=ScreenManager.
    //        Draw(gameTime, ScreenManager.SpriteBatch);
    //        ScreenManager.SpriteBatch.End();
    //    }
        
        
    //    public virtual void Draw(GameTime gameTime,SpriteBatch batch)
    //    {
    //        CreamXGame.Instance.GameTime = gameTime;
    //        if (ScreenState == ScreenState.Active && TransitionPosition ==0)
    //        {
    //            if (CreamXGameEngine.Instance.SceneManager.CurrentScene != null)
    //            {
    //                CreamXGameEngine.Instance.EngineRender((float)gameTime.ElapsedGameTime.TotalSeconds,batch);
    //            }
    //        }
    //        // If the game is transitioning on or off, fade it out to black.
    //        if (TransitionPosition > 0)
    //        {
    //           // ScreenManager.SpriteBatch.Begin();
    //            ScreenManager.FadeBackBufferToBlack(255 - TransitionAlpha,batch);
    //            //ScreenManager.SpriteBatch.End();
    //        }
    //    }


        

    //    #endregion
    //}
}
